/**
 * 
 */
package es.cloudcast.persistence.jdo.action.basic;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import es.cloudcast.persistence.PersistenceException;
import es.cloudcast.persistence.dao.jdo.PersistenceManagerFactory;
import es.cloudcast.persistence.jdo.action.Action;

/**
 * Counts all elements of type clazz
 * 
 * @author Samuel García Martínez <in0de>
 *
 */
public class CountAction implements Action {

	protected Class<?> clazz;
	
	public CountAction(Class<?> clazz) {
		this.clazz = clazz;
	}
	
	/* (non-Javadoc)
	 * @see es.cloudcast.persistence.jdo.action.Action#process(es.cloudcast.persistence.jdo.PersistenceManagerFactory)
	 */
	public Object process(PersistenceManagerFactory PMF)
			throws PersistenceException {
		Integer result = null;
		
		try {
			PersistenceManager pManager = 
				PMF.getCurrentPersistenceManager();
			Query query = pManager.newQuery(clazz);
			query.setResult("count(*)");
			
			result = (Integer) query.execute();
		} catch(Exception ex) {
			throw new PersistenceException(ex);
		}
		
		return result;
	}

}
